﻿#region Using directives

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using AviFile;
using System.Threading;

#endregion

namespace AviDemo {
    partial class MainForm : Form {
        private AviHandler handler = null;
        AviPlayer aaa;
        private int currentFrameIndex;
        private bool isRun = false;

        [STAThread]
        public static void Main() {
            Application.Run(new MainForm());
        }
        
        public MainForm() {
            InitializeComponent();
            handler = new AviHandler();
        }

        private void btnExtract_Click(object sender, System.EventArgs e) 
        {
            if (folderDialog.ShowDialog() == DialogResult.OK)
                handler.ExtractImages(txtSourceName.Text, folderDialog.SelectedPath);
        }

        private void btnCompress_Click(object sender, System.EventArgs e) {
            fileSaveDlg.Filter = "Avi Files|*.avi";
            if (fileSaveDlg.ShowDialog() == DialogResult.OK)
            {
                String dest = fileSaveDlg.FileName;
                AddMessage("Сжатие " + txtSourceName.Text + " to " + dest);
                handler.CopyFile(txtSourceName.Text, dest, true);
                AddMessage("Сжатие завершено");
            }
        }

        private void numPosition_ValueChanged(object sender, System.EventArgs e) {
            ShowFrame(sender);
        }

        private void ShowFrame(object sender) 
        {
            try 
            {
                picFrame.Image = handler.GetFrame(txtSourceName.Text, rbSelect.RangeMaximum);
                errorProvider1.Clear();
            } 
            catch (Exception ex) 
            {
                /*NumericUpDown updown = sender as NumericUpDown;
                if (updown != null)
                {
                    updown.ValueChanged -= numPosition_ValueChanged;
                    updown.Value--;
                    updown.ValueChanged += numPosition_ValueChanged;
                }*/
                errorProvider1.SetError(sender as Control, ex.Message);
            }
        }

        private void btnSelectFile_Click(object sender, System.EventArgs e) 
        {
            fileOpenDlg.Filter = "Avi Files|*.avi";
            if (fileOpenDlg.ShowDialog(this) == DialogResult.OK)
            {
                EnableButtons(true);
                infoBox.Items.Clear();
                txtSourceName.Text = fileOpenDlg.FileName;
                AddMessage(handler.ReadInfo(fileOpenDlg.FileName));
                rbSelect.Enabled = true;
                //sbMain.Maximum = handler.FrameCount - 1;
                ShowFrame(sender);
                rbSelect.DivisionNum = handler.FrameCount;
                rbSelect.TotalMinimum = 0;
                rbSelect.TotalMaximum = handler.FrameCount - 1;
                rbSelect.RangeMinimum = 0;
                rbSelect.RangeMaximum = 0;

            }
            else
                txtSourceName.Text = null;
        }

        private void Form1_Load(object sender, System.EventArgs e) {
        }

        private void btnExtractWave_Click(object sender, System.EventArgs e) 
        {
            fileSaveDlg.Filter = "Sound Files|*.wav";
            if (fileSaveDlg.ShowDialog() == DialogResult.OK)
            {
                AddMessage("Extracting " + txtSourceName.Text + " to sound.wav");
                try
                {
                    handler.ExtractAudio(txtSourceName.Text, fileSaveDlg.FileName);
                    AddMessage("Extracting audio finished.");
                    errorProvider1.Clear();
                }
                catch (Exception ex)
                {
                    errorProvider1.SetError(sender as Control, "The file does not contain a wave audio stream, or it cannot be opened.\r\n" + ex.ToString());
                }
            }
        }

        private void btnAddSound_Click(object sender, System.EventArgs e) {
            fileOpenDlg.Filter = "Sound Files|*.wav";
            if (fileOpenDlg.ShowDialog(this) == DialogResult.OK)
            {
                String soundFileName = fileOpenDlg.FileName;
                AddMessage("Adding to sound.wav to " + soundFileName);
                try
                {
                    handler.AddSound(txtSourceName.Text, soundFileName, Convert.ToInt32(numInsertWavePosition.Value));
                    errorProvider1.Clear();
                }
                catch(IndexOutOfRangeException ex)
                {
                    errorProvider1.SetError(sender as Control, ex.Message);
                }
                catch (Exception ex)
                {
                    errorProvider1.SetError(sender as Control, "The file does not accept the new wave audio stream. " + ex.Message);
                }
                AddMessage("Adding sound finished.");
            }
        }

        private void btnExtractVideo_Click(object sender, System.EventArgs e) 
        {
            fileSaveDlg.Filter = "Avi Files|*.avi";
            if (fileSaveDlg.ShowDialog() == DialogResult.OK)
            {
                AddMessage("Extracting " + txtSourceName.Text + " to " + fileSaveDlg.FileName);
                handler.ExtractVideo(txtSourceName.Text, fileSaveDlg.FileName);
                AddMessage("Extracting video finished.");
            }
        }

        private void EnableButtons(bool isEnabled)
        {
            btnCompress.Enabled = isEnabled;
            btnExtract.Enabled = isEnabled;
            btnExtractVideo.Enabled = isEnabled;
            btnExtractWave.Enabled = isEnabled;
            btnAddSound.Enabled = isEnabled;
        }

        private void AddMessage(String message)
        {
            infoBox.Items.Add(message);
            infoBox.SetSelected(infoBox.Items.Count - 1, true);
        }

        private void AddMessage(List<String> messages)
        {
            int oldCount = infoBox.Items.Count;
            infoBox.Items.AddRange(messages.ToArray());
            infoBox.SetSelected(oldCount + 1, true);
        }

        private void sbMain_ValueChanged(object sender, EventArgs e)
        {
            ShowFrame(sender);
        }

        private void btnPlay_Click(object sender, EventArgs e)
        {
            if (aaa==null || !aaa.IsRunning)
                aaa = new AviPlayer(handler.stream, picFrame, null);

            aaa.Start(rbSelect);
            isRun = true;
        }

        private void btmStop_Click(object sender, EventArgs e)
        {
            aaa.Stop();
            isRun = false;
        }

        private void btnPause_Click(object sender, EventArgs e)
        {
            if (isRun)
            {
                currentFrameIndex = aaa.CurrentFrameIndex;
                aaa.Stop();
                isRun = false;
            }
            else
            {
                aaa.CurrentFrameIndex = currentFrameIndex;
                aaa.Resume();
                isRun = true;
            }
        }

        private void button1_Click(object sender, EventArgs e)
        {
            AviManager aviManager = new AviManager(txtSourceName.Text, true);
            //AviManager newFile = aviManager.CopyTo("videocopy.avi", (float)numStart.Value, (float)numStop.Value);
            fileSaveDlg.Filter = "Avi Files|*.avi";
            if (fileSaveDlg.ShowDialog() == DialogResult.OK)
            {
                Thread thread = new Thread(new ThreadStart(delegate() { CutFrame(aviManager); }));
                thread.Start();
            }

            
            aviManager.Close();
            
            
        }

        private void CutFrame(AviManager aviManager)
        {
            AviManager newFile = aviManager.CopyTo(fileSaveDlg.FileName, (float)rbSelect.RangeMinimum, (float)rbSelect.RangeMaximum);
            newFile.Close();
            MessageBox.Show("Сохранение завершено");
        }

        private void button2_Click(object sender, EventArgs e)
        {
            CreateAviForm newAvi = new CreateAviForm(handler, txtSourceName.Text);
            newAvi.Show();

        }

        private void zzzzRangeBar1_RangeChanged(object sender, EventArgs e)
        {
            ShowFrame(sender);
        }

        private void zzzzRangeBar1_RangeChanging(object sender, EventArgs e)
        {
            ShowFrame(sender);
        }

        private void zzzzRangeBar1_Scroll(object sender, ScrollEventArgs e)
        {
            ShowFrame(sender);
        }
    }
}